// 密码辅助工具 - 用于测试和管理
const bcrypt = require('bcryptjs');
const pool = require('../config/database');

/**
 * 生成密码哈希（用于创建/重置密码）
 * @param {String} plainPassword - 明文密码
 * @returns {String} 哈希后的密码
 */
async function hashPassword(plainPassword) {
  return await bcrypt.hash(plainPassword, 10);
}

/**
 * 验证密码
 * @param {String} plainPassword - 明文密码
 * @param {String} hashedPassword - 哈希密码
 * @returns {Boolean} 是否匹配
 */
async function verifyPassword(plainPassword, hashedPassword) {
  return await bcrypt.compare(plainPassword, hashedPassword);
}

/**
 * 查看用户的密码哈希（仅用于调试）
 * @param {String} phone - 手机号
 * @returns {Object} 用户信息和密码哈希
 */
async function getUserPasswordHash(phone) {
  const [users] = await pool.execute(
    'SELECT id, phone, password_hash, nickname, role FROM users WHERE phone = ?',
    [phone]
  );

  if (users.length === 0) {
    return { found: false, message: '用户不存在' };
  }

  return {
    found: true,
    userId: users[0].id,
    phone: users[0].phone,
    nickname: users[0].nickname,
    role: users[0].role,
    passwordHash: users[0].password_hash || null,
    hasPassword: !!users[0].password_hash
  };
}

/**
 * 重置用户密码
 * @param {String} phone - 手机号
 * @param {String} newPassword - 新密码
 * @returns {Object} 操作结果
 */
async function resetUserPassword(phone, newPassword) {
  try {
    const [users] = await pool.execute(
      'SELECT id FROM users WHERE phone = ?',
      [phone]
    );

    if (users.length === 0) {
      return { success: false, message: '用户不存在' };
    }

    const hashedPassword = await hashPassword(newPassword);

    await pool.execute(
      'UPDATE users SET password_hash = ?, failed_login_attempts = 0, locked_until = NULL WHERE id = ?',
      [hashedPassword, users[0].id]
    );

    return {
      success: true,
      message: '密码重置成功',
      userId: users[0].id,
      phone: phone
    };
  } catch (error) {
    return {
      success: false,
      message: '密码重置失败: ' + error.message
    };
  }
}

/**
 * 批量查看所有用户的密码哈希状态（仅用于调试）
 * @returns {Array} 用户列表
 */
async function getAllUsersPasswordStatus() {
  const [users] = await pool.execute(
    'SELECT id, phone, nickname, role, password_hash IS NOT NULL as has_password FROM users ORDER BY id'
  );

  return users.map(user => ({
    id: user.id,
    phone: user.phone,
    nickname: user.nickname,
    role: user.role,
    hasPassword: user.has_password === 1
  }));
}

module.exports = {
  hashPassword,
  verifyPassword,
  getUserPasswordHash,
  resetUserPassword,
  getAllUsersPasswordStatus
};

